import React, { useState, useEffect } from 'react';
import { ConnectProps, connect, Dispatch, useRequest } from 'umi';
import {
  Row,
  Col,
  Button,
  Card,
  Form,
  Input,
  Tree,
  Popover,
  Popconfirm,
  Select,
  Spin,
  message,
} from 'antd';
import { FormInstance } from 'antd/lib/form';
import { EventDataNode } from 'antd/lib/tree';
import { PageContainer } from '@ant-design/pro-layout';

import arrToTree from 'array-to-tree';
import { api } from '@/services/config';
import { permissions, sortPermission } from '../service';
import { PermissionItem, TreeNodeItem } from '../data';

interface PermissionProps extends ConnectProps {
  // rbac: PermissionItem;
  dispatch: Dispatch;
}

const { TreeNode } = Tree;
const { Option } = Select;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};
const Permission: React.FC<PermissionProps> = ({ dispatch }) => {
  const formRef = React.createRef<FormInstance>();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(false);

  const { data: permissionList, run, loading } = useRequest(api.system.permissions);

  const onDrop = async (info: {
    event: React.MouseEvent;
    node: EventDataNode & any;
    dragNode: EventDataNode & any;
    dragNodesKeys: React.Key[];
    dropPosition: number;
    dropToGap: boolean;
  }) => {
    const dropKey = info.node.props.eventKey;
    const dragKey = info.dragNode.props.eventKey;
    const dropPos = info.node.pos.split('-');
    // console.log(dropKey + '===' + dragKey + '===' + JSON.stringify(dropPos));
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    const dropItem = permissionList.filter((el: PermissionItem) => el.id === dragKey);
    const dragItem = permissionList.filter((el: PermissionItem) => el.id === dropKey);
    if (dropItem.parentId !== dragItem.parentId || dropPosition === 0) {
      message.error('只能在同一级移动调换顺序');
    } else if (dropItem === dragItem) {
      message.error('顺序未发生变化');
    } else {
      const data = {
        dropId: dropKey,
        dragId: dragKey,
      };
      const { code } = await sortPermission(data);
      if (code === 0) {
        message.success('排序成功');
        run();
      }
    }
  };

  const renderTreeData = (data: PermissionItem[]) => {
    // console.log(JSON.stringify(data));
    return data.map((item: PermissionItem) => {
      const title = (
        <Popover content={renderPopoverContent(item)} placement="right" trigger="click">
          <span>{item.menuName}</span>
        </Popover>
      );
      if (item.children) {
        return (
          <TreeNode key={item.id} title={title} style={{ padding: '4px 0' }}>
            {renderTreeData(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={title} style={{ padding: '4px 0' }} />;
    });
  };

  const renderPopoverContent = (item: PermissionItem) => (
    <div>
      <p>
        <Button size="small" onClick={() => onAdd(item)}>
          添加
        </Button>
      </p>
      <p>
        <Button size="small" onClick={() => onEdit(item)}>
          修改
        </Button>
      </p>
      <p>
        <Popconfirm
          title="是否确定删除当前节点?"
          onConfirm={() => onDelete(item)}
          okText="是"
          cancelText="否"
        >
          <Button type="primary" size="small" danger>
            删除
          </Button>
        </Popconfirm>
      </p>
      <p hidden={!!item.parentId}>
        <Button type="primary" size="small" onClick={() => ({})}>
          添加一级权限
        </Button>
      </p>
    </div>
  );

  // 添加权限
  const onAdd = (item: PermissionItem) => {
    formRef.current?.resetFields();
    formRef.current?.setFieldsValue({
      parentId: item && item.id,
      parentName: getParentName(item.id),
      // menuLevel: item && (item.permissionLevel || 0) + 1,
    });
  };

  // 修改权限
  const onEdit = (item: PermissionItem) => {
    formRef.current?.resetFields();
    formRef.current?.setFieldsValue({
      ...item,
      parentName: getParentName(item.parentId),
    });
  };

  const getParentName = (parentId: string | undefined) => {
    if (parentId) {
      return permissionList.find((x: PermissionItem) => x.id === parentId)?.menuName || null;
    }
    return null;
  };

  // 删除
  const onDelete = async (item: PermissionItem) => {
    if (item.children && item.children.length > 0) {
      message.error('请先删除子节点');
      return;
    }
    const data = {
      method: 'DELETE',
      id: item.id,
    };
    const { code } = await permissions(data);
    if (code === 0) {
      message.success('删除成功');
      //刷新tree
      run();
    }
  };

  // 修改or新增
  const handleAdd = () => {
    formRef.current?.validateFields().then(async (values) => {
      const { id } = values;
      const data = {
        method: id ? 'put' : 'post',
        ...values,
      };
      const { code } = await permissions(data);
      if (code === 0) {
        message.success(id ? '更新成功' : '保存成功');
        //刷新tree
        run();
      }
    });
  };

  return (
    <PageContainer title={false}>
      <Card style={{ minHeight: 'calc(100vh - 190px)' }}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col sm={24} md={8}>
            <Spin spinning={loading}>
              <Tree
                showLine
                draggable
                autoExpandParent={autoExpandParent}
                expandedKeys={expandedKeys}
                onDrop={onDrop}
                onExpand={(keys: React.Key[]) => {
                  setExpandedKeys(keys);
                  setAutoExpandParent(false);
                }}
              >
                {renderTreeData(
                  arrToTree(permissionList ? permissionList : [], {
                    parentProperty: 'parentId',
                    customID: 'id',
                  }),
                )}
              </Tree>
            </Spin>
          </Col>
          <Col sm={24} md={8}>
            <Form layout="horizontal" ref={formRef} onFinish={handleAdd}>
              <Form.Item hidden name="id" />
              <Form.Item hidden name="parentId" />
              <Form.Item
                label="名称"
                name="menuName"
                rules={[{ required: true, message: '名称不能为空!' }]}
                {...formItemLayout}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="权限码"
                name="componentName"
                rules={[{ required: true, whitespace: true, message: '权限码不能为空!' }]}
                {...formItemLayout}
              >
                <Input />
              </Form.Item>
              <Form.Item label="父节点" name="parentName" {...formItemLayout}>
                <Input disabled />
              </Form.Item>
              <Form.Item
                label="类型"
                name="type"
                rules={[{ required: true, message: '类型不能为空!' }]}
                {...formItemLayout}
              >
                <Select placeholder="请选择">
                  <Option value={0}>菜单</Option>
                  <Option value={1}>功能</Option>
                </Select>
              </Form.Item>
              {/* <Form.Item label="备注" name="remark" {...formItemLayout}>
                <Input.TextArea autoSize={{ minRows: 2, maxRows: 6 }} />
              </Form.Item> */}
              <Form.Item wrapperCol={{ span: 12, offset: 6 }}>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Card>
    </PageContainer>
  );
};

export default Permission;
